package com.example.check_in.util;

import com.example.redis.utils.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import static com.example.model.constants.KeyConstants.KEY_INCR;

@Component
public class IdWorker {

    @Autowired
    private CacheUtil cacheUtil;

    private static final long START_STAMP = 1640995200L; // 2022-01-01 00:00:00 UTC
    private static final int BUSINESS_BITS = 8; // 业务标识占8位
    private static final int SEQUENCE_BITS = 24; // 自增序列占24位
    private static final Map<String, Long> BUSINESS_CODE_MAP = new HashMap<>();

    static {
        BUSINESS_CODE_MAP.put("order", 1L);
        BUSINESS_CODE_MAP.put("payment", 2L);
        BUSINESS_CODE_MAP.put("schedule", 3L);
        BUSINESS_CODE_MAP.put("deposit", 4L);
    }

    public long getId(String prefix) {
        // 获取业务编码
        Long businessCode = BUSINESS_CODE_MAP.get(prefix);
        if (businessCode == null) {
            throw new IllegalArgumentException("Invalid prefix: " + prefix);
        }

        // 计算时间戳部分
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.toEpochSecond(ZoneOffset.UTC) - START_STAMP;

        // 生成序列号（每日独立）
        String dateKey = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String redisKey = KEY_INCR + prefix + ":" + dateKey;
        long sequence = cacheUtil.incr(redisKey);

        // 组合业务编码和序列号
        long businessPart = (businessCode & 0xFFL) << SEQUENCE_BITS; // 高8位为业务编码
        long sequencePart = sequence & 0x00FFFFFFL; // 低24位为序列号
        long combined = businessPart | sequencePart;

        // 拼接时间戳和组合值
        return (timestamp << (BUSINESS_BITS + SEQUENCE_BITS)) | combined;
    }
}